import curses
import os
import time
from threading import Thread
import signal

def key_listener(stdscr):
    # 初始化 curses 设置
    stdscr.keypad(False)  # 禁用特殊键序列转换
    curses.cbreak()
    curses.noecho()
    stdscr.nodelay(True)  # 非阻塞模式
    
    print("按键监听已启动... (q退出) - 程序在后台运行")
    print("提示信息不会清屏，正常终端输出不受影响")
    
    while not exit_flag.is_set():
        # 尝试获取按键
        c = stdscr.getch()
        
        if c != -1:  # -1 表示无按键
            # 特殊按键处理
            if c == curses.KEY_UP: key = "↑"
            elif c == curses.KEY_DOWN: key = "↓"
            elif c == curses.KEY_LEFT: key = "←"
            elif c == curses.KEY_RIGHT: key = "→"
            elif c == 10: key = "Enter"
            elif c == 27: key = "ESC"
            elif c == 127: key = "Backspace"
            elif c == 9: key = "Tab"
            elif c == 113:  # 'q' 键
                print("\n检测到退出指令")
                break
            else:
                try:
                    key = chr(c)
                except:
                    key = f"Unknown({c})"
            
            # 这里改成您的处理逻辑
            # 比如可以记录到文件，而不是打印到终端
            with open("key_log.txt", "a") as f:
                f.write(f"{time.strftime('%H:%M:%S')} - 按键: {key}\n")
        
        time.sleep(0.05)  # 减少CPU占用

# 全局退出标志
exit_flag = None

def main(stdscr):
    # 设置信号处理
    def sig_handler(signum, frame):
        exit_flag.set()
        print("\n收到信号，退出中...")
    signal.signal(signal.SIGINT, sig_handler)
    signal.signal(signal.SIGTERM, sig_handler)
    
    global exit_flag
    exit_flag = signal.Event()
    
    # 启动按键监听线程
    listener = Thread(target=key_listener, args=(stdscr,))
    listener.daemon = True
    listener.start()
    
    # 主线程保持运行
    print("程序正在运行...按 q 退出或 CTRL+C")
    while not exit_flag.is_set() and listener.is_alive():
        time.sleep(1)
    
    print("清理并退出程序")

if __name__ == "__main__":
    # 使用 wrapper 确保终端恢复
    curses.wrapper(main)
    print("程序已退出")